package com.dragon.modules.yuegou.service.impl.message;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.message.MessageEntity;
import com.dragon.modules.yuegou.enums.MsgType;
import com.dragon.modules.yuegou.enums.Platform;
import com.dragon.modules.yuegou.enums.message.MessageChannel;
import com.dragon.modules.yuegou.enums.message.MessageFromType;
import com.dragon.modules.yuegou.enums.message.MessageSystemType;
import com.dragon.modules.yuegou.enums.message.MessageToType;
import com.dragon.modules.yuegou.mapper.message.MessageMapper;
import com.dragon.modules.yuegou.model.member.Member;
import com.dragon.modules.yuegou.model.message.Message;
import com.dragon.modules.yuegou.query.message.MessageQuery;
import com.dragon.modules.yuegou.service.member.MemberService;
import com.dragon.modules.yuegou.service.message.MessageService;
import com.dragon.modules.yuegou.utils.PageToResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-18 13:46:09
 * @version 2.0
 */
@Slf4j
@Service("msgMessageService")
public class MessageServiceImpl
		extends ServiceImpl<MessageMapper, MessageEntity>
		implements MessageService {

	@Autowired
	private MemberService memberService;
	@Override
	public Message noread(String toUser) {
		MessageQuery query = new MessageQuery();
		query.toUser().eq(toUser);
		query.fromType().eq(MessageFromType.SYSTEM);
		query.reached().eq(Boolean.FALSE);

		Message message = new Message();
		Long noReadTotal =count(query.toQueryWrapper());
		message.setNoReadTotal(noReadTotal.intValue());
		return message;
	}

	@Override
	public boolean isReachedMessage(String userId) {
		if (userId==null){
			return false;
		}
		MessageQuery query = new MessageQuery();
		query.setToUser(userId);
		query.setReached(false);
		return count(query.toQueryWrapper())>0;
	}

	@Override
	public IPage<Message> messageRecord(PageRequest page, MessageQuery query) {
		QueryWrapper<MessageEntity> queryWrapper =  query.toQueryWrapper();
		queryWrapper.orderByDesc(MessageEntity.COL_CREATED_TIME);
		return page(PageToResultUtils.resultToPage(page), queryWrapper);
	}

	@Override
	public List<Message> messageRecord(Integer fromType, String toUser) {
		List<Message> list = baseMapper.messageRecord(toUser, fromType);
		list.stream().forEach(this::fillMemberInfo);
		return list;
	}

	private void fillMemberInfo(Message message){
		Member member = memberService.getMember(message.getFromUser());
		if (null != member){
			message.setFromImg(member.getHeadImg());
			message.setNickName(member.getNickName());

			MessageQuery query = new MessageQuery();
			query.setToUser(message.getToUser());
			query.setFromUser(message.getFromUser());
			List<MessageEntity> list = list(query.toQueryWrapper());
			if (CollectionUtils.isNotEmpty(list)){
				MessageEntity temp = list.get(list.size() - 1);
				message.setContent(temp.getContent());
				message.setLastMsgTime(temp.getCreatedTime());
			}
			message.setReached(message.getMesTotal().intValue() - message.getRecived().intValue() == 0);
			message.setNoReadTotal(message.getMesTotal().intValue() - message.getRecived().intValue());
		}
	}

	@Override
	public Message messageInfo(String messageId) {
		MessageEntity message = getById(messageId);
		if (null != message && message.getChannel().equals(MessageChannel.SYSTEM)){ //系统站内信：读时才算触达
			message.setReached(true);
			message.setReachedTime(LocalDateTime.now());
			updateById(message);
		}
		return new Message(message);
	}

	@Override
	public IPage<Message> systemMsg(PageRequest page,String memberId,String toId) {
		List<Message> messages = new ArrayList<>();
		//查询点赞和关注信息
		MessageQuery messageQuery = new MessageQuery();
		messageQuery.setPlatform(Platform.YSQ_APP);
		messageQuery.setFromType(MessageFromType.SYSTEM);
		messageQuery.setToType(MessageToType.MEMBER);
		messageQuery.setToUser(toId);
		//查询该会员接收系统消息数量
		messageQuery.setSystemType(null);
		messageQuery.setReached(null);
		List<MessageSystemType> systemTypes = new ArrayList<>();
		systemTypes.add(MessageSystemType.EXPIRED);
		systemTypes.add(MessageSystemType.LSSUE);
		systemTypes.add(MessageSystemType.REFUND);
		messageQuery.systemType().in(systemTypes);
		IPage<Message> iPage = page(PageToResultUtils.resultToPage(page), messageQuery.toQueryWrapper());
		messages.addAll(iPage.getRecords());
		iPage.setRecords(messages);
		return iPage;
	}
	@Override
	@Transactional
	public IPage<Message> dialogueMsg(PageRequest page,String fromId,String toId) {
		IPage<Message> iPage = baseMapper.dialogueMsg(PageToResultUtils.resultToPage(page), fromId, toId);
		List<Message> records = iPage.getRecords();
		for (Message message : records) {
			Member member = memberService.getMember(message.getFromUser());
			if (null != member) {
				message.setFromImg(member.getHeadImg());
				message.setNickName(member.getNickName());
			}

			if (Boolean.FALSE.equals(message.getReached())) {
				message.setReached(true);
				message.setReachedTime(LocalDateTime.now());
				updateById(message);
			}
		}
		records = records.stream().sorted(Comparator.comparing(Message::getCreatedTime)).collect(Collectors.toList()); // 按时间排序
		iPage.setRecords(records);
		return iPage;
	}

	@Override
	@Transactional
	public IPage<Message> dialogueMsgNotDel(PageRequest page, String fromId,String toId) {
		IPage<Message> messageIPage = PageToResultUtils.resultToPage(page);
		IPage<Message> iPage = baseMapper.dialogueMsgNotDel(messageIPage, fromId, toId);
		List<Message> records = iPage.getRecords();
		for (Message message : records) {
			Member member = memberService.getMember(message.getFromUser());
			if (null != member) {
				message.setFromImg(member.getHeadImg());
				message.setNickName(member.getNickName());
			}

			if (Boolean.FALSE.equals(message.getReached())) {
				message.setReached(true);
				message.setReachedTime(LocalDateTime.now());
				updateById(message);
			}
		}
		records = records.stream().sorted(Comparator.comparing(Message::getCreatedTime)).collect(Collectors.toList()); // 按时间排序
		iPage.setRecords(records);
		return iPage;
	}

	@Override
	public void messageReply(Platform platform, String toId, String content, MessageChannel messageChannel,
							 MsgType msgType,String fromUser) {
		Message message = new Message();

		message.setPlatform(platform);
		message.setFromType(MessageFromType.MEMBER);
		if(StringUtils.isNotBlank(fromUser)){
			message.setFromUser(fromUser);
		}else {
			message.setFromUser("1");
		}

		message.setToType(MessageToType.MEMBER);
		message.setToUser(toId);
		message.setChannel(messageChannel);
		message.setMsgType(msgType);
		message.setContent(content);
		message.setReached(false);
		
		save(message);
	}

	@Override
	public List<Message> turnList(String merchantId) {
		return baseMapper.turnList(merchantId);
	}

	@Override
	public void delInfo(String fromId, String toId) {
		//逻辑删除
		//删除消息发送人为fromid 接收者是toid
		baseMapper.delFormIdSend(fromId, toId);
		//删除消息接收人是fromid 发送者是toid
		baseMapper.delFormIdAccept(fromId, toId);
	}

	@Override
	public Boolean setHasNewMessage(String busdId, String memberId) {
		MessageQuery messageQuery = new MessageQuery();
		messageQuery.toUser().eq(memberId);
		messageQuery.toDel().eq(false);
		messageQuery.reached().eq(false);
		return this.count(messageQuery.toQueryWrapper()) > 0;
	}
}